package com.example.hxds.bff.driver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.bff.driver.controller.form.*;
import com.example.hxds.bff.driver.feign.*;
import com.example.hxds.bff.driver.service.OrderService;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.PageUtils;
import com.example.hxds.common.util.R;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.HashMap;

/**
 * @Author XUYANG
 * @Date 2024-03-20 19:34
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderServiceApi orderServiceApi;
    @Resource
    private CstServiceApi cstServiceApi;
    @Resource
    private NebulaServiceApi nebulaServiceApi;
    @Resource
    private RuleServiceApi ruleServiceApi;
    @Resource
    private SnmServiceApi snmServiceApi;
    @Override
    @Transactional
    @LcnTransaction
    public String acceptNewOrder(AcceptNewOrderForm form) {
        R r=orderServiceApi.acceptNewOrder(form);
        String res= MapUtil.getStr(r,"result");
        return res;
    }

    @Override
    public HashMap searchDriverExecuteOrder(SearchDriverExecuteOrderForm form) {
        R r=orderServiceApi.searchDriverExecuteOrder(form);
        HashMap orderMap= (HashMap) r.get("result");

        //查询代驾客户信息
        long customerId=MapUtil.getLong(orderMap,"customerId");
        SearchCustomerInfoInOrderForm infoInOrderForm=new SearchCustomerInfoInOrderForm();
        infoInOrderForm.setCustomerId(customerId);
        r=cstServiceApi.searchCustomerInfoInOrder(infoInOrderForm);
        HashMap cstMap= (HashMap) r.get("result");

        HashMap res=new HashMap();
        res.putAll(orderMap);
        res.putAll(cstMap);
        return res;
    }
    @Override
    public HashMap searchDriverCurrentOrder(SearchDriverCurrentOrderForm form) {
        R r=orderServiceApi.searchDriverCurrentOrder(form);
        HashMap orderMap= (HashMap) r.get("result");
        if (MapUtil.isNotEmpty(orderMap)){
            HashMap res=new HashMap();
            //查询代驾客户信息
            long customerId=MapUtil.getLong(orderMap,"customerId");
            SearchCustomerInfoInOrderForm cusForm =new SearchCustomerInfoInOrderForm();
            cusForm.setCustomerId(customerId);
            r = cstServiceApi.searchCustomerInfoInOrder(cusForm);
            HashMap cstMap= (HashMap) r.get("result");
            res.putAll(orderMap);
            res.putAll(cstMap);
            return res;
        }else {
            return null;
        }

    }

    @Override
    public HashMap searchOrderForMoveById(SearchOrderForMoveByIdForm form) {
        R r=orderServiceApi.searchOrderForMoveById(form);
        HashMap res=(HashMap) r.get("result");
        return res;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int arriveStartPlace(ArriveStartPlaceForm form) {
        R r=orderServiceApi.arriveStartPlace(form);
        int rows=MapUtil.getInt(r,"rows");
        if (rows==1){
            //TODO 发出消息通知乘客
        }
        return rows;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int startDriving(StartDrivingForm form) {
        R r=orderServiceApi.startDriving(form);
        int rows=MapUtil.getInt(r,"rows");
        if (rows==1){
            InsertOrderMonitoringForm m_form=new InsertOrderMonitoringForm();
            m_form.setOrderId(form.getOrderId());
            nebulaServiceApi.insertOrderMonitoring(m_form);
            //TODO 发送通知消息
        }

        return rows;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int updateOrderStatus(UpdateOrderStatusForm form) {
        R r=orderServiceApi.updateOrderStatus(form);
        int rows=MapUtil.getInt(r,"rows");
        //判断订单状态，然后实现后续业务
        if (rows!=1){
            throw new HxdsException("订单状态修改失败");
        }
        if (form.getStatus()==6){
            SendPrivateMessageForm form1=new SendPrivateMessageForm();
            form1.setReceiverIdentity("customer_bill");
            form1.setReceiverId(form.getCustomerId());
            form1.setTtl(3*24*3600*1000);
            form1.setSenderId(0L);
            form1.setSenderIdentity("system");
            form1.setSenderName("华夏代驾");
            form1.setMsg("您有代驾订单待支付");
            snmServiceApi.sendPrivateMessageSync(form1);
        }
        return rows;
    }

    @Override
    public int updateOrderBill(UpdateBillFeeForm form) {
        //判断司机是否关联该订单
        ValidDriverOwnOrderForm form1=new ValidDriverOwnOrderForm();
        form1.setOrderId(form.getOrderId());
        form1.setDriverId(form.getDriverId());
        R r=orderServiceApi.validDriverOwnOrder(form1);
        boolean valid=MapUtil.getBool(r,"result");
        if (!valid){
            throw new HxdsException("司机未关联该订单");
        }

        CalculateOrderMileageForm form2=new CalculateOrderMileageForm();
        form2.setOrderId(form.getOrderId());
        r=nebulaServiceApi.calculateOrderMileage(form2);
        String mileage=(String) r.get("result");
        mileage=NumberUtil.div(mileage,"1000",1, RoundingMode.CEILING).toString();

        SearchSettlementNeedDataForm form3=new SearchSettlementNeedDataForm();
        form3.setOrderId(form.getOrderId());
        r=orderServiceApi.searchSettlementNeedData(form3);
        HashMap map=(HashMap)r.get("result");
        String acceptTime=MapUtil.getStr(map,"acceptTime");
        String startTime=MapUtil.getStr(map,"startTime");
        int waitingMinute=MapUtil.getInt(map,"waitingMinute");
        String favourFee=MapUtil.getStr(map,"favourFee");

        CalculateOrderChargeForm form4=new CalculateOrderChargeForm();
        form4.setMileage(mileage);
        form4.setTime(startTime.split(" ")[1]);
        form4.setMinute(waitingMinute);
        r = ruleServiceApi.calculateOrderCharge(form4);
        map=(HashMap)r.get("result");
        String mileageFee=MapUtil.getStr(map,"mileageFee");
        String returnFee=MapUtil.getStr(map,"returnFee");
        String waitingFee=MapUtil.getStr(map,"waitingFee");
        String amount=MapUtil.getStr(map,"amount");
        String returnMileage=MapUtil.getStr(map,"returnMileage");

        CalculateIncentiveFeeForm form_5 = new CalculateIncentiveFeeForm();
        form_5.setDriverId(form.getDriverId());
        form_5.setAcceptTime(acceptTime);
//        r = ruleServiceApi.calculateIncentiveFee(form_5);
        String incentiveFee = "0.00";

        form.setMileageFee(mileageFee);
        form.setReturnFee(returnFee);
        form.setWaitingFee(waitingFee);
        form.setIncentiveFee(incentiveFee);
        form.setRealMileage(mileage);
        form.setReturnMileage(returnMileage);
        //计算总费用
        String total = NumberUtil.add(amount, form.getTollFee(), form.getParkingFee(), form.getOtherFee(), favourFee).toString();
        form.setTotal(total);

        CalculateProfitsharingForm form_6 = new CalculateProfitsharingForm();
        form_6.setOrderId(form.getOrderId());
        form_6.setAmount(total);
        r = ruleServiceApi.calculateProfitsharing(form_6);
        map = (HashMap) r.get("result");
        long ruleId = MapUtil.getLong(map, "ruleId");
        String systemIncome = MapUtil.getStr(map, "systemIncome");
        String driverIncome = MapUtil.getStr(map, "driverIncome");
        String paymentRate = MapUtil.getStr(map, "paymentRate");
        String paymentFee = MapUtil.getStr(map, "paymentFee");
        String taxRate = MapUtil.getStr(map, "taxRate");
        String taxFee = MapUtil.getStr(map, "taxFee");

        form.setRuleId(ruleId);
        form.setPaymentRate(paymentRate);
        form.setPaymentFee(paymentFee);
        form.setTaxRate(taxRate);
        form.setTaxFee(taxFee);
        form.setSystemIncome(systemIncome);
        form.setDriverIncome(driverIncome);

        r = orderServiceApi.updateBillFee(form);
        int rows = MapUtil.getInt(r, "rows");
        return rows;
    }

    @Override
    public HashMap searchReviewDriverOrderBill(SearchReviewDriverOrderBillForm form) {
        R r=orderServiceApi.searchReviewDriverOrderBill(form);
        HashMap map=(HashMap) r.get("result");
        return map;
    }

    @Override
    public Integer searchOrderStatus(SearchOrderStatusForm form) {
        R r=orderServiceApi.searchOrderStatus(form);
        Integer status=(Integer) r.get("result");
        return status;
    }

    @Override
    @Transactional
    @LcnTransaction
    public String updateOrderAboutPayment(long driverId, UpdateOrderAboutPaymentForm form) {
        ValidDriverOwnOrderForm validForm=new ValidDriverOwnOrderForm();
        validForm.setDriverId(driverId);
        validForm.setOrderId(form.getOrderId());
        R r=orderServiceApi.validDriverOwnOrder(validForm);
        boolean bool=MapUtil.getBool(r,"result");
        if (!bool){
            throw new HxdsException("司机未关联该订单");
        }
        r=orderServiceApi.updateOrderAboutPayment(form);
        String result=MapUtil.getStr(r,"result");
        return result;
    }

    @Override
    public PageUtils searchDriverOrderByPage(SearchDriverOrderByPageForm form) {
        R r=orderServiceApi.searchDriverOrderByPage(form);
        HashMap map=(HashMap) r.get("result");
        PageUtils pageUtils= BeanUtil.toBean(map,PageUtils.class);
        return pageUtils;
    }

    @Override
    public HashMap searchOrderById(SearchOrderByIdForm form) {
        R r=orderServiceApi.searchOrderById(form);
        HashMap orderMap=(HashMap) r.get("result");
        //查询代驾客户信息
        long customerId=MapUtil.getLong(orderMap,"customerId");
        SearchCustomerInfoInOrderForm form1=new SearchCustomerInfoInOrderForm();
        form1.setCustomerId(customerId);
        r=cstServiceApi.searchCustomerInfoInOrder(form1);
        HashMap cstMap= (HashMap) r.get("result");
        int status=MapUtil.getInt(orderMap,"status");
        HashMap cmtMap=new HashMap<>();
        if (status==7||status==8){
            SearchCommentByOrderIdForm form2=new SearchCommentByOrderIdForm();
            form2.setOrderId(form.getOrderId());
            form2.setDriverId(form.getDriverId());
            r=orderServiceApi.searchCommentByOrderId(form2);

            if (r.containsKey("result")){
                cmtMap=(HashMap) r.get("result");
            }else {
                cmtMap.put("rate",5);
            }
        }
        HashMap res=new HashMap<>();
        res.putAll(orderMap);
        res.putAll(cstMap);
        res.put("comment",cmtMap);
        return res;
    }

    @Override
    public String searchCommentIdByOrderId(SearchCommentIdByOrderIdForm form) {
        R r=orderServiceApi.searchCommentIdByOrderId(form);
        String res=MapUtil.getStr(r,"result");
        return res;
    }
}
